import base64
import pickle
from django_redis import get_redis_connection


def merge_cookie_to_redis(request,user,response):

    cookie_str = request.COOKIES.get("cart")
    if cookie_str is not None:
        cookie_cart = pickle.loads(base64.b64decode(cookie_str))

        redis_conn = get_redis_connection('cart')
        sku_id_counts = redis_conn.hgetall('cart_%s' % user.id)

        selected_ids = []
        redis_count_ids = {}

        for sku_id,count in sku_id_counts.items():
            redis_count_ids[int(sku_id)] = int(count)

        for sku_id,count_selected in cookie_cart.items():

            if sku_id in redis_count_ids:
                redis_count_ids[sku_id] = count_selected["count"]
            else:
                redis_count_ids[sku_id] = count_selected["count"]

            if count_selected["selected"]:
                selected_ids.append(sku_id)

        redis_conn.hmset('cart_%s' % user.id, redis_count_ids)
        redis_conn.sadd('cart_selected_%s' % user.id, *selected_ids)
        response.delete_cookie('cart')

        return response
    else:
        return response